package com.voiceqsologger.service;

import com.voiceqsologger.config.AsrApiProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.core.io.ByteArrayResource;

import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 简单的云端 API 识别客户端：将音频字节以 multipart/form-data 方式上传到硅流接口。
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ApiAsrClient {

    private final AsrApiProperties apiProperties;
    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 调用云端接口识别音频文件。
     * @param audioPath 本地音频文件路径
     * @return 文本结果
     */
    public String transcribe(Path audioPath) {
        try {
            byte[] audio = Files.readAllBytes(audioPath);
            return transcribe(audio, "audio.wav");
        } catch (Exception e) {
            throw new RuntimeException("读取音频失败", e);
        }
    }

    /**
     * 调用云端接口识别音频字节。
     * @param audioBytes 音频字节
     * @param filename 文件名
     * @return 文本结果
     */
    public String transcribe(byte[] audioBytes, String filename) {
        String apiKey = apiProperties.getApiKey();
        if (apiKey == null || apiKey.isEmpty()) {
            apiKey = System.getenv("SILICONFLOW_API_KEY");
        }
        if (apiKey == null || apiKey.isEmpty()) {
            throw new IllegalStateException("未配置 asr.api.apiKey 且未设置环境变量 SILICONFLOW_API_KEY");
        }

        String url = apiProperties.getTranscriptionUrl();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.set("Authorization", "Bearer " + apiKey);

        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        ByteArrayResource filePart = new ByteArrayResource(audioBytes) {
            @Override
            public String getFilename() {
                return filename;
            }
        };
        body.add("file", filePart);
        body.add("model", apiProperties.getModel());

        HttpEntity<MultiValueMap<String, Object>> req = new HttpEntity<>(body, headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(url, req, String.class);
        if (!resp.getStatusCode().is2xxSuccessful()) {
            throw new RuntimeException("API 调用失败，code=" + resp.getStatusCodeValue() + ", body=" + resp.getBody());
        }
        // 简单提取返回 text 字段（接口与 OpenAI 兼容时为 { text: "..." }）
        String bodyStr = resp.getBody();
        if (bodyStr == null) return "";
        String text = extractTextField(bodyStr);
        return text == null ? bodyStr : text;
    }

    // 轻量级 JSON 提取，避免额外依赖
    private String extractTextField(String json) {
        try {
            int idx = json.indexOf("\"text\"");
            if (idx < 0) return null;
            int colon = json.indexOf(':', idx);
            if (colon < 0) return null;
            int startQuote = json.indexOf('"', colon + 1);
            int endQuote = json.indexOf('"', startQuote + 1);
            if (startQuote < 0 || endQuote < 0) return null;
            return json.substring(startQuote + 1, endQuote);
        } catch (Exception e) {
            log.warn("extract text field failed", e);
            return null;
        }
    }
}


